package com.cz.mydao.wrapper;

import com.cz.mydao.constant.SqlKey;
import com.cz.mydao.util.MyUtil;
import lombok.Getter;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @descriptions: 查询条件封装类
 * @author: Joker.
 * @date: 2024/12/25 16:31
 * @version: 1.0
 */

public class SelectWrapper extends AbstractWrapper<SelectWrapper> {

    /**
     * 存储查询列
     */
    private final List<String> selectColumns = new ArrayList<>();

    /**
     * 排序条件
     */
    @Getter
    protected String orderBy;

    /**
     * 是否去重
     */
    protected boolean distinct;

    /**
     * 设置去重
     *
     * @param distinct 是否去重
     */
    public void distinct(boolean distinct) {
        this.distinct = distinct;
    }

    /**
     * 设置查询列
     * @param columns 查询结果列
     * @return 调用者本身
     */
    public SelectWrapper select(String... columns) {
        Collections.addAll(this.selectColumns, columns);
        return this;
    }

    /**
     * 设置排序条件
     * @param column 排序列
     * @param ascending 正序倒序
     * @return 调用者本身
     */
    public SelectWrapper orderBy(String column, boolean ascending) {
        this.orderBy = column + (ascending ? SqlKey.ASC : SqlKey.DESC);
        return this;
    }

    /**
     * 构建查询sql
     * @param tableName 表名
     * @return sql
     */
    @Override
    public String buildSql(String tableName) {
        StringBuilder sqlBuilder = new StringBuilder(SqlKey.SELECT);
        // 设置是否去重
        if (distinct) {
            sqlBuilder.append(SqlKey.DISTINCT);
        }
        // 如果指定查询列，设置查询列
        if (!selectColumns.isEmpty()) {
            for (int i = 0; i < selectColumns.size(); i++) {
                sqlBuilder.append(selectColumns.get(i));
                if (i < selectColumns.size() - 1) {
                    sqlBuilder.append(SqlKey.COMMA);
                }
            }
        }
        sqlBuilder.append(SqlKey.FROM).append(tableName);

        // 拼接 WHERE 条件
        if (!conditions.isEmpty()) {
            // 构建where条件
            MyUtil.buildWhereSql(conditions, sqlBuilder);
        }
        // 添加逻辑删除条件
        sqlBuilder.append(SqlKey.AND)
                .append(SqlKey.IS_DELETE)
                .append(SqlKey.EQUALS)
                .append(SqlKey.ZERO);
        // 拼接 ORDER BY 条件
        if (orderBy != null) {
            sqlBuilder.append(SqlKey.ORDER_BY).append(orderBy);
        }
        return sqlBuilder.toString();
    }

}